//
//  StatusPictureView.swift
//  新浪微博01
//
//  Created by 李国伟 on 15/12/12.
//  Copyright © 2015年 李国伟. All rights reserved.
//

import UIKit
import SDWebImage
let resuseID = "PictureCell"
let StatusLineMargin: CGFloat = 8
class StatusPictureView: UICollectionView,UICollectionViewDataSource,UICollectionViewDelegate{

    var viewModel: StatusViewModel?{
        didSet{
            sizeToFit()
            
            //为了防止collectionCell的重用
            reloadData()
        }
    }
    
     init() {
        let layout = UICollectionViewFlowLayout()
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        dataSource = self
        delegate = self
        registerClass(StatuspictureCell.self, forCellWithReuseIdentifier: resuseID)
        layout.minimumInteritemSpacing = StatusLineMargin
        layout.minimumLineSpacing = StatusLineMargin
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //sizeToFit调用的方法
    override func sizeThatFits(size: CGSize) -> CGSize {
        
        return  calcViewSize()
    }
}

///  数据源方法
extension StatusPictureView {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return viewModel?.thumbnailUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = dequeueReusableCellWithReuseIdentifier(resuseID, forIndexPath: indexPath) as? StatuspictureCell
        
        cell?.url = viewModel?.thumbnailUrls![indexPath.row]
       return cell!
    }
    
    ///  代理方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let userInfo = [WBSelectedPictureIndexPath: indexPath, WBSelectedPictureURLs: viewModel!.thumbnailUrls!]
        
        NSNotificationCenter.defaultCenter().postNotificationName(WBSelectedPictureNotification, object: self, userInfo: userInfo)
    }
}


///  计算collectionview的真实大小
extension StatusPictureView {
    
    
    private func calcViewSize() ->CGSize{
        
    //算出item的大小，并设置
        let rowcount: CGFloat = 3
        
    //根据屏幕计算
        let itemwith = ((UIScreen.mainScreen().bounds.width - 2 * StatusLineMargin - 2 * StatusCellMargin)  / 3) - 1
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSizeMake(itemwith, itemwith)
        
    //计算图片的数量根据数量的不同返回不同的contentView的大小
      let count = viewModel?.thumbnailUrls?.count ?? 0
        
        if count == 0 {
            layout.itemSize = CGSizeMake(1, 1)
            return CGSizeZero
        }
        
        if count == 1{
            
            // TODO: - 临时指定大小，稍后再讲
            
            let key = viewModel?.thumbnailUrls![0].absoluteString
            //从缓存中取出图片的大小
          let image =   SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            
            guard let img = image else {
                return CGSizeZero
            }
            let  size = img.size
            
            //判断极限情况
            size.height < 40 ? 40 : size.height
            
            size.width > 300 ? 300 : size.width
            
            // 内部图片的大小
            layout.itemSize = size
            
            // 配图视图的大小
            return size

        }
        
        if count == 4{
            
            let w = 2 * itemwith + 2 * StatusLineMargin
            
            return CGSizeMake(w, w)
        }
        
        let rownumber  = CGFloat((count - 1) / Int(rowcount) + 1)
        
        let height = rownumber * itemwith + (rownumber - 1) * StatusLineMargin
       
        let width = itemwith * rowcount + (rowcount - 1) * StatusLineMargin
        
        return CGSizeMake(width + 1, height)
    }
}

//MARK: 代理方法
extension StatusPictureView: PhotoBrowserPresentDelegate {
    
    func presentImage(indexPath: NSIndexPath) -> UIImageView {
        
        let iv = UIImageView()
        
        iv.contentMode = .ScaleAspectFill
        iv.clipsToBounds = true
        
        let key = viewModel!.thumbnailUrls![indexPath.item].absoluteString
        iv.image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
        
        iv.sizeToFit()
        
        return iv

    }
    
    //计算起始位置
    func presentStartRect(indexPath: NSIndexPath) -> CGRect {
        
      guard let cell = self.cellForItemAtIndexPath(indexPath) else{
        
         return CGRectZero
        }
        
      let rect = self.convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        
        return rect
    }
    
    //计算结束位置
    func presentEndRect(indexPath: NSIndexPath) -> CGRect {
        
        let key = viewModel?.thumbnailUrls![indexPath.item].absoluteString
        let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
        let w = UIScreen.mainScreen().bounds.width
        let h = image.size.height * w / image.size.width
        
        var y: CGFloat = 0
        let screenH = UIScreen.mainScreen().bounds.height
        if h > screenH {
            
            y = 0
        }else {
            
            y = (screenH - h) * 0.5
        }
        
        return CGRectMake(0, y, w, h)
    }
}

//自定义cell
class StatuspictureCell: UICollectionViewCell{
    
    var url: NSURL? {
        didSet{
           iconView.sd_setImageWithURL(url, placeholderImage: nil, options: [.RetryFailed,.RefreshCached])
            let str = (url!.absoluteString as NSString).pathExtension.lowercaseString as NSString
            gifView.hidden = !str.isEqualToString("gif")
        }
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //添加子控件设置约束
    private func setupUI(){
    
    //如果直接添加cell会无法重用
      contentView.addSubview(iconView)
      contentView.addSubview(gifView)
        gifView.sizeToFit()
       iconView.snp_makeConstraints { (make) -> Void in
        make.edges.equalTo(contentView.snp_edges)
        }
        
      iconView.contentMode = .ScaleToFill
      iconView.layer.masksToBounds = true
        
        gifView.snp_makeConstraints { (make) -> Void in
          make.right.equalTo(contentView)
          make.bottom.equalTo(contentView)
        }
    }
    //懒加载控件
    private lazy var iconView = UIImageView()
    private lazy var gifView = UIImageView(image:UIImage(named: "timeline_image_gif"))
}
